//
//  MapManager.m
//  PigMarket
//
//  Created by mac on 2019/5/20.
//  Copyright © 2019 felix.pigmarket.oc. All rights reserved.
//

#import "LocationManager.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>

@interface LocationManager ()<CLLocationManagerDelegate, MKMapViewDelegate, AMapSearchDelegate>

@property (nonatomic, assign) BOOL isFirstLocation;

@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) MKMapView *mapView;
@property (nonatomic, strong) CLLocation *useLocation; //当前地址
@property (nonatomic, strong) AMapPOI *aimMapPOI; //默认选择地址数据
@property (nonatomic, strong) AMapPOI *fristMapPOI; //定位地址数据

@property (nonatomic, strong) AMapSearchAPI *search;
@property (nonatomic, strong) NSMutableArray *locations; //当前维度

@property (nonatomic, assign) double lat;
@property (nonatomic, assign) double lon;


@end

static LocationManager *instance = nil;

@implementation LocationManager

+ (instancetype)sharedManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[LocationManager alloc] init];
    });
    return instance;
}


#pragma mark - AMapSearchAPI
- (void)manageSearchNearByLocation{
    
    [instance initSearchManager];
    @weakify(self);
    [instance startLocationCompleteBlock:^(double latitude, double longitude) {
        @strongify(self);
        self.lat = latitude;
        self.lon = longitude;
        [self addSearchs];
    }];
}


- (void)initSearchManager{
    _search = [[AMapSearchAPI alloc] init];
    _search.delegate = self;
}

#pragma mark - 附近搜索数据
- (void)addSearchs{
    AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
    request.location = [AMapGeoPoint locationWithLatitude:self.lat longitude:self.lon];
    //request.types = @"汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施";
    request.sortrule = 0;
//    request.radius = 1000;
    // request.keywords = keywords;
    request.requireExtension = YES;
    [self.search AMapPOIAroundSearch:request];
}


#pragma mark - 附近搜索数据回调
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response{
    
    if (response.pois.count == 0) {
        return;
    }
    
    if (response.pois.count>0) {
        _locations = [response.pois mutableCopy];
        [_locations enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            AMapPOI *mapPoi = (AMapPOI *)obj;
            NSString *address = [NSString stringWithFormat:@"%@%@%@", mapPoi.city, mapPoi.district, mapPoi.address];
            mapPoi.address = address;
        }];
        
        if (self.locationSearchBlock) {
            self.locationSearchBlock([self.locations copy]);
        }
    }
}


//#pragma mark -
//
//- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated{
//
////    if (!animated && !_isFristPositioning ) {
////        self.isFristPositioning = YES;
////    }
//}
//
//- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
//
//    [self.locationManager stopUpdatingLocation];
//
//    CLLocationCoordinate2D coordinate;
//    coordinate.latitude = userLocation.location.coordinate.latitude;
//    coordinate.longitude = userLocation.location.coordinate.longitude;
//
//
////    if (_isUpdateLocation) {
////        _isUpdateLocation = NO;
////        [self hideProgressView];
////        [self setMapRegionWithCoordinate:coordinate];
////    }
//}
//
//
//- (void)setMapRegionWithCoordinate:(CLLocationCoordinate2D)coordinate{
//
//    MKCoordinateRegion region;
//    region = MKCoordinateRegionMake(coordinate, MKCoordinateSpanMake(.01, .01));
//    MKCoordinateRegion adjustedRegion = [_mapView regionThatFits:region];
//   // _isFristPositioning = YES;
//    [_mapView setRegion:adjustedRegion animated:YES];
//}
//
//
////更新用户位置，只要用户改变则调用此方法（包括第一次定位到用户位置）
//- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated { // 调用获取中心点坐标代理方法
//
//    [self.locationManager stopUpdatingLocation];
//
//    MKCoordinateRegion region;
//    CLLocationCoordinate2D centerCoordinate2D = mapView.region.center;
//    region.center = centerCoordinate2D;
//
//
//   // self.isFristPositioning = NO;
//    CLLocation *location = [[CLLocation alloc] initWithLatitude:centerCoordinate2D.latitude longitude:centerCoordinate2D.longitude];
//    self.useLocation = location;
//
//    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
//
//    kWeakSelf(self);
//    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
//
//        CLPlacemark *place = [placemarks firstObject];
//
//        weakself.fristMapPOI = [[AMapPOI alloc] init];
//        //            NSString *address = [NSString stringWithFormat:@"%@%@%@", place.locality, place.subLocality, place.name];
//        //            weakself.fristMapPOI.address = address;
//        //            weakself.fristMapPOI.location.latitude = place.location.coordinate.latitude;
//        //            weakself.fristMapPOI.location.longitude = place.location.coordinate.longitude;
//        //
//        //            NSLog(@"%@%@%@%@",place.administrativeArea, place.locality, place.subLocality, place.name);
//        //            NSLog(@"%@%@%lf%lf",place.thoroughfare, place.subLocality, place.location.coordinate.latitude, place.location.coordinate.latitude);
//        //            NSLog(@"%@", weakself.fristMapPOI.address);
//
//
//
//        //            weakself.currentProvince = [weakself checkIsNull:place.administrativeArea];
//        //            weakself.currentCity = [weakself checkIsNull:place.locality];
//        //            weakself.currentArea = [weakself checkIsNull:place.subLocality];
//        //
//        //            NSString *placename = [weakself checkIsNull:place.name];
//        //            NSString *thoroughfare = [weakself checkIsNull:place.thoroughfare];
//        //            NSString *subThoroughfare = [weakself checkIsNull:place.subThoroughfare];
//        //
//        //
//        //            if ([place.name containsString: place.thoroughfare]) {
//        //                weakself.row_three_textview.text = thoroughfare;
//        //            }else{
//        //                weakself.row_three_textview.text = [NSString stringWithFormat:@"%@%@%@",placename, thoroughfare, subThoroughfare];
//        //            }
//
//    }];
//
//    [self initSearchs];
//
//    //[self bigPinAnimation];
//
//}


- (void)initLocationManager {
    
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.distanceFilter = 10.0f;
    [self.locationManager requestWhenInUseAuthorization];
    [self.locationManager startUpdatingLocation];
}


- (void)startLocation
{
    self.isFirstLocation = YES;
    if ([CLLocationManager locationServicesEnabled]) { //定位是否允许
        [self initLocationManager];
    }
}

- (void)startLocationCompleteBlock:(void (^)(double, double))completeBlock {
    
    self.isFirstLocation = YES;
    if ([CLLocationManager locationServicesEnabled]) {
        [self initLocationManager];
        self.locationResultBlock = completeBlock;
    } else {
        completeBlock(0,0);
    }
}


//重新定位
- (void)resetLocation
{
    [self.locationManager startUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    
    if (self.isFirstLocation) {
        
        CLLocation *currentLocation = [locations lastObject];
        if (self.locationResultBlock) {
            self.isFirstLocation = NO;
            self.locationResultBlock(currentLocation.coordinate.latitude, currentLocation.coordinate.longitude);
        }
        
        //反向地理编码
        CLGeocoder *geoCoder = [[CLGeocoder alloc] init];
        [geoCoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            
            if (error ||placemarks.count == 0) {
                
            }else{
                
                CLPlacemark *fristPlacemark = [placemarks firstObject];
                if (self.locationNameBlock) {
                    self.locationNameBlock(fristPlacemark.name, self.lat, self.lon);
                }
            }
        }];
    }
}


- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    
    if ([error code] == kCLErrorDenied){
        if (self.locationResultBlock) {
            self.locationResultBlock(0,0);
        }
    }
    if ([error code] == kCLErrorLocationUnknown) {
        if (self.locationResultBlock) {
            self.locationResultBlock(0,0);
        }
    }
}


#pragma mark - getter methods
//添加地图控件
- (MKMapView *)mapView{
    
    if (!_mapView) {
        
        _mapView = [[MKMapView alloc]initWithFrame:CGRectZero];
       // _mapView.size = CGSizeMake(KScreenWidth, mapViewMaxH);
        _mapView.mj_x = 0;
        _mapView.mj_y = 0;
        _mapView.delegate = self;
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
        [_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
        
        if(![CLLocationManager locationServicesEnabled]||[CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedWhenInUse){
            [_locationManager requestWhenInUseAuthorization];
        }
        _mapView.userTrackingMode = MKUserTrackingModeFollow;
        _mapView.mapType = MKMapTypeStandard;
        
        //大头针
       // [_mapView addSubview:self.bigPin];
        
        //重新定位Icon
//        [_mapView addSubview:self.resetPositionIcon];
//        _resetPositionIcon.mj_y = _mapView.height - _resetPositionIcon.width - 15;
        
    }
    return _mapView;
}


- (NSMutableArray *)locations{
    
    if (!_locations) {
        _locations = [NSMutableArray array];
    }
    return _locations;
}

////大头针
//- (UIImageView *)bigPin
//{
//    if (!_bigPin) {
//
//        _bigPin = [[UIImageView alloc] init];
//        _bigPin.image = [UIImage imageNamed:@"shop_icon_dw"];
//        _bigPin.size = CGSizeMake(20, 40);
//        _bigPin.mj_x = KScreenWidth/2.0 - 10;
//        _bigPin.mj_y = mapViewMaxH/2.0 - 40;
//    }
//    return _bigPin;
//}


@end
